package com.common;

import com.service.user.LogService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**  */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

  @Autowired LogService logService;

  @ExceptionHandler(value = Exception.class)
  public Result<String> globalException(Exception exception) {
    exception.printStackTrace();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    exception.printStackTrace(new PrintStream(baos));
    try {
      // 数据库添加错误日志
      logService.addAErrorLog(exception.getClass().getName(), baos.toString());
    } catch (Exception e) {
      System.out.println();
      System.err.println("-----------------------------------------------");
      System.err.println("错误日志接口错误！！！");
      e.printStackTrace();
    }
    return Result.serverError(exception.getLocalizedMessage());
  }
}
